package data

import (
	"fmt"
	"time"
	"yunj/app/model"
	"yunj/app/service/client/logdbservice"
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/enum/stateenum"
	yunjModel "yunj/pkg/yunj/app/model"
	"yunj/pkg/yunj/core/db"

	"gorm.io/gorm"
)

// 初始化博客数据库
func InitBlogDbData() (err error) {
	// ad
	if err = initAdDbData(); err != nil {
		return
	}
	// article
	if err = initArticleDbData(); err != nil {
		return
	}
	// article_attr
	if err = initArticleAttrDbData(); err != nil {
		return
	}
	// category
	if err = initCategoryDbData(); err != nil {
		return
	}
	// category数据准备
	if err = CategoryPrepareOrReset(); err != nil {
		return
	}
	// guid
	if err = initGuidDbData(); err != nil {
		return
	}
	// link
	if err = initLinkDbData(); err != nil {
		return
	}
	// 日志表创建
	if err = logdbservice.TablePrepare(); err != nil {
		return
	}
	return
}

func initAdDbData() (err error) {
	modelDb := db.Model(&model.Ad{})
	tableName := modelDb.GetTableName()
	// 创建数据表
	tableSql := "CREATE TABLE IF NOT EXISTS `" + tableName + "` (" +
		"`id` int unsigned NOT NULL AUTO_INCREMENT," +
		"`location` tinyint unsigned NOT NULL DEFAULT '0' COMMENT '位置'," +
		"`cover` varchar(100) NOT NULL DEFAULT '' COMMENT '封面'," +
		"`link` varchar(200) NOT NULL DEFAULT '' COMMENT '链接'," +
		"`desc` varchar(200) NOT NULL DEFAULT '' COMMENT '描述'," +
		"`sort` tinyint unsigned NOT NULL DEFAULT '0' COMMENT '排序'," +
		"`valid_time` int unsigned NOT NULL COMMENT '截止有效期'," +
		"`create_time` int unsigned NOT NULL," +
		"`last_update_time` int unsigned NOT NULL," +
		"`status` tinyint unsigned NOT NULL DEFAULT '11' COMMENT '数据状态：11待发布、22已发布'," +
		"`state` tinyint unsigned NOT NULL DEFAULT '11' COMMENT '数据状态：11正常、22回收站、99删除'," +
		"PRIMARY KEY (`id`) USING BTREE," +
		"KEY `idx_state_location_desc` (`state`,`location`,`desc`) USING BTREE," +
		"KEY `idx_state_location_status_desc` (`state`,`location`,`status`,`desc`) USING BTREE" +
		") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC COMMENT='广告表';"
	err = global.MySQL.Exec(tableSql).Error
	if err != nil {
		err = fmt.Errorf("创建数据表%s失败！%v", tableName, err)
	}
	return
}

func initArticleDbData() (err error) {
	modelDb := db.Model(&model.Article{})
	tableName := modelDb.GetTableName()
	// 创建数据表
	tableSql := "CREATE TABLE IF NOT EXISTS `" + tableName + "` (" +
		"`id` int unsigned NOT NULL AUTO_INCREMENT," +
		"`category_id` int unsigned NOT NULL DEFAULT '0' COMMENT '分类'," +
		"`title` varchar(200) NOT NULL COMMENT '标题'," +
		"`cover` varchar(100) NOT NULL DEFAULT '' COMMENT '封面'," +
		"`keywords` varchar(200) NOT NULL DEFAULT '' COMMENT '关键词'," +
		"`view_count` int unsigned NOT NULL DEFAULT '0'," +
		"`create_time` int unsigned NOT NULL," +
		"`last_update_time` int unsigned NOT NULL," +
		"`status` tinyint unsigned NOT NULL DEFAULT '11' COMMENT '数据状态：11草稿、22已发布'," +
		"`state` tinyint unsigned NOT NULL DEFAULT '11' COMMENT '数据状态：11正常、22回收站、99删除'," +
		"PRIMARY KEY (`id`) USING BTREE," +
		"KEY `idx_state_title` (`state`,`title`) USING BTREE," +
		"KEY `idx_state_status_title` (`state`,`status`,`title`) USING BTREE" +
		") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC COMMENT='文章表';"
	err = global.MySQL.Exec(tableSql).Error
	if err != nil {
		err = fmt.Errorf("创建数据表%s失败！%v", tableName, err)
	}
	return
}

func initArticleAttrDbData() (err error) {
	modelDb := db.Model(&model.ArticleAttr{})
	tableName := modelDb.GetTableName()
	// 创建数据表
	tableSql := "CREATE TABLE IF NOT EXISTS `" + tableName + "` (" +
		"`article_id` int unsigned NOT NULL," +
		"`content` text NOT NULL COMMENT '标题'," +
		"PRIMARY KEY (`article_id`) USING BTREE" +
		") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC COMMENT='文章属性表';"
	err = global.MySQL.Exec(tableSql).Error
	if err != nil {
		err = fmt.Errorf("创建数据表%s失败！%v", tableName, err)
	}
	return
}

// 默认分类
var DefaultCategory *model.Category

func initCategoryDbData() (err error) {
	modelDb := db.Model(&model.Category{})
	tableName := modelDb.GetTableName()
	// 创建数据表
	tableSql := "CREATE TABLE IF NOT EXISTS `" + tableName + "` (" +
		"`id` int unsigned NOT NULL AUTO_INCREMENT," +
		"`pid` int unsigned NOT NULL DEFAULT '0'," +
		"`pids` json DEFAULT NULL COMMENT '所有的父级id'," +
		"`level` int unsigned NOT NULL DEFAULT '1' COMMENT '等级'," +
		"`name` varchar(100) NOT NULL DEFAULT '' COMMENT '名称'," +
		"`alias` varchar(100) NOT NULL DEFAULT '' COMMENT '别名'," +
		"`img` varchar(200) NOT NULL DEFAULT '' COMMENT '图片'," +
		"`desc` varchar(200) NOT NULL DEFAULT '' COMMENT '描述'," +
		"`sort` smallint unsigned NOT NULL DEFAULT '0' COMMENT '排序'," +
		"`create_time` int unsigned NOT NULL," +
		"`last_update_time` int unsigned NOT NULL," +
		"`state` tinyint unsigned NOT NULL DEFAULT '11' COMMENT '数据状态：11正常、22回收站、99删除'," +
		"PRIMARY KEY (`id`) USING BTREE," +
		"UNIQUE KEY `uk_alias` (`alias`) USING BTREE," +
		"KEY `idx_id_state` (`id`,`state`) USING BTREE" +
		") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC COMMENT='分类表';"
	err = global.MySQL.Exec(tableSql).Error
	if err != nil {
		err = fmt.Errorf("创建数据表%s失败！%v", tableName, err)
	}
	// 判断默认分类数据是否存在，不存在则加入
	var defaultCategory model.Category
	dbErr := global.MySQL.Model(&model.Category{}).Where("`alias` = ?", global.Config.Default.Category.Alias).First(&defaultCategory).Error
	if dbErr != nil && dbErr != gorm.ErrRecordNotFound {
		err = fmt.Errorf("数据表%s默认数据是否存在查询异常！%v", tableName, dbErr)
		return
	}
	if dbErr == gorm.ErrRecordNotFound {
		defaultCategory = model.Category{
			Pid:   global.Config.Default.Category.Pid,
			Pids:  yunjModel.Uint64SliceJson{},
			Name:  global.Config.Default.Category.Name,
			Alias: global.Config.Default.Category.Alias,
			Img:   global.Config.Default.Category.Img,
		}
		currTime := time.Now().In(time.Local).Unix()
		defaultCategory.CreateTime = currTime
		defaultCategory.LastUpdateTime = currTime
		defaultCategory.State = stateenum.NORMAL
		dbErr = global.MySQL.Save(&defaultCategory).Error
		if dbErr != nil {
			err = fmt.Errorf("数据表%s默认insert数据异常！%v", tableName, dbErr)
			return
		}
	}
	return
}

func initGuidDbData() (err error) {
	modelDb := db.Model(&model.Guid{})
	tableName := modelDb.GetTableName()
	// 创建数据表
	tableSql := "CREATE TABLE IF NOT EXISTS `" + tableName + "` (" +
		"`id` bigint unsigned NOT NULL COMMENT 'guid'," +
		"`create_time` int unsigned NOT NULL," +
		"PRIMARY KEY (`id`) USING BTREE" +
		") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC COMMENT='全局唯一ID表';"
	err = global.MySQL.Exec(tableSql).Error
	if err != nil {
		err = fmt.Errorf("创建数据表%s失败！%v", tableName, err)
	}
	return
}

func initLinkDbData() (err error) {
	modelDb := db.Model(&model.Link{})
	tableName := modelDb.GetTableName()
	// 创建数据表
	tableSql := "CREATE TABLE IF NOT EXISTS `" + tableName + "` (" +
		"`id` int unsigned NOT NULL AUTO_INCREMENT," +
		"`link` varchar(200) NOT NULL DEFAULT '' COMMENT '链接'," +
		"`desc` varchar(200) NOT NULL DEFAULT '' COMMENT '描述'," +
		"`sort` tinyint unsigned NOT NULL DEFAULT '0' COMMENT '排序'," +
		"`create_time` int unsigned NOT NULL," +
		"`last_update_time` int unsigned NOT NULL," +
		"`status` tinyint unsigned NOT NULL DEFAULT '11' COMMENT '数据状态：11待发布、22已发布'," +
		"`state` tinyint unsigned NOT NULL DEFAULT '11' COMMENT '数据状态：11正常、22回收站、99删除'," +
		"PRIMARY KEY (`id`) USING BTREE," +
		"KEY `idx_state_desc` (`state`,`desc`) USING BTREE," +
		"KEY `idx_state_status_desc` (`state`,`status`,`desc`) USING BTREE" +
		") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC COMMENT='链接表';"
	err = global.MySQL.Exec(tableSql).Error
	if err != nil {
		err = fmt.Errorf("创建数据表%s失败！%v", tableName, err)
	}
	return
}
